//
//  LoginViewController.m
//  XRSquare
//
//  Created by UaenaMo on 2018/7/26.
//  Copyright © 2018年 UaenaMo. All rights reserved.
//

#import "LoginViewController.h"
#import "HomeViewController.h"
#import "SortViewController.h"
#import "GrowViewController.h"
#import "MyViewController.h"
#import "RegisterViewController.h"
#import "LoginAccountViewController.h"
#import <UMShare/UMShare.h>
@import CoreLocation;
#define IOS8 [[[UIDevice currentDevice] systemVersion]floatValue]>=8.0

@interface LoginViewController ()<CLLocationManagerDelegate>
{
    NSString * province;
    NSString * city;
}
@property(nonatomic,retain)CLLocationManager *locationManager;
@end

@implementation LoginViewController

//开始定位
-(void)locationStart{
    //判断定位操作是否被允许
    
    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init] ;
        self.locationManager.delegate = self;
        //设置定位精度
        self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = kCLLocationAccuracyHundredMeters;//每隔多少米定位一次（这里的设置为每隔百米)
        if (IOS8) {
            //使用应用程序期间允许访问位置数据
            [self.locationManager requestWhenInUseAuthorization];
        }
        // 开始定位
        [self.locationManager startUpdatingLocation];
    }else {
        //提示用户无法进行定位操作
        NSLog(@"%@",@"定位服务当前可能尚未打开，请设置打开！");
        
    }
}
#pragma mark - CoreLocation Delegate

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

{
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [self.locationManager stopUpdatingLocation];
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    
    //获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count >0)
         {
             
             [[NSUserDefaults
               standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-hans",
                                                nil] forKey:@"AppleLanguages"];
             
             CLPlacemark *placemark = [array objectAtIndex:0];
             //获取城市
             NSString *currCity = placemark.locality;
             if (!currCity) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 currCity = placemark.administrativeArea;
             }
             
             province = placemark.administrativeArea;
             city = currCity;
             
         } else if (error ==nil && [array count] == 0)
         {
             NSLog(@"No results were returned.");
         }else if (error !=nil)
         {
             NSLog(@"An error occurred = %@", error);
         }
         
     }];
    
}
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    if (error.code ==kCLErrorDenied) {
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
    }
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    province = @"辽宁省";
    city = @"大连市";
    
    self.navigationController.navigationBarHidden = YES;
    
    UIImageView * backImage = [[UIImageView alloc]initWithFrame:self.view.bounds];
    backImage.image = [UIImage imageNamed:@"lb"];
    [self.view addSubview:backImage];

    UIImageView * logoImage = [[UIImageView alloc]initWithFrame:CGRectMake(20, ScreenHeight/2 - 220, 100, 80)];
    logoImage.image = [UIImage imageNamed:@"logo-p"];
    [self.view addSubview:logoImage];
    
    UILabel * titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, ScreenHeight/2 - 95, ScreenWidth, 25)];
    titleLabel.font = [UIFont systemFontOfSize:26 weight:UIFontWeightLight];
    titleLabel.text = @"欢迎来到蓄锐广场";
    [self.view addSubview:titleLabel];
    
    UILabel * subLabel = [[UILabel alloc]initWithFrame:CGRectMake(80, ScreenHeight/2 - 40, ScreenWidth, 20)];
    subLabel.font = [UIFont systemFontOfSize:20 weight:UIFontWeightUltraLight];
    subLabel.text = @"——我的成长伴侣";
    [self.view addSubview:subLabel];

    UIButton * login = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - 90, 20, 80, 40)];
    [login setTitle:@"登录" forState:UIControlStateNormal];
    login.titleLabel.font = [UIFont systemFontOfSize:15];
    [login setTitleColor:themeColor forState:UIControlStateNormal];
    [login addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:login];
    
    
    UIButton * wechatLogin = [[UIButton alloc]initWithFrame:CGRectMake(20, ScreenHeight/2 + 30, ScreenWidth - 40, 40)];
    wechatLogin.layer.borderColor = themeColor.CGColor;
    wechatLogin.layer.borderWidth = 1;
    wechatLogin.layer.cornerRadius = 20;
    wechatLogin.clipsToBounds = YES;
    [wechatLogin setTitleColor:themeColor forState:UIControlStateNormal];
    [wechatLogin setTitle:@"微信登录" forState:UIControlStateNormal];
    [wechatLogin addTarget:self action:@selector(wechatLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:wechatLogin];
    
    UIButton * qqLogin = [[UIButton alloc]initWithFrame:CGRectMake(20, wechatLogin.frame.size.height + wechatLogin.frame.origin.y + 10, ScreenWidth - 40, 40)];
    qqLogin.layer.borderColor = themeColor.CGColor;
    qqLogin.layer.borderWidth = 1;
    qqLogin.layer.cornerRadius = 20;
    qqLogin.clipsToBounds = YES;
    [qqLogin setTitleColor:themeColor forState:UIControlStateNormal];
    [qqLogin setTitle:@"qq登录" forState:UIControlStateNormal];
    [qqLogin addTarget:self action:@selector(qqLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:qqLogin];
    
    UIButton * home = [[UIButton alloc]initWithFrame:CGRectMake(20, qqLogin.frame.size.height + qqLogin.frame.origin.y + 10, ScreenWidth - 40, 40)];
    home.layer.borderColor = themeColor.CGColor;
    home.layer.borderWidth = 1;
    home.layer.cornerRadius = 20;
    home.clipsToBounds = YES;
    [home setTitleColor:themeColor forState:UIControlStateNormal];
    [home setTitle:@"进首页看看" forState:UIControlStateNormal];
    [home addTarget:self action:@selector(home) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:home];
    
    UIButton * create = [[UIButton alloc]initWithFrame:CGRectMake(20, home.frame.size.height + home.frame.origin.y + 10, ScreenWidth - 40, 40)];
    create.layer.borderColor = themeColor.CGColor;
    create.layer.borderWidth = 1;
    create.layer.cornerRadius = 20;
    create.clipsToBounds = YES;
    [create setTitleColor:themeColor forState:UIControlStateNormal];
    [create setTitle:@"创建账号" forState:UIControlStateNormal];
    [create addTarget:self action:@selector(create) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:create];
    
    UILabel * tiaojkuan = [[UILabel alloc]initWithFrame:CGRectMake(20, create.frame.origin.y + 50, ScreenWidth - 20, 20)];
    tiaojkuan.font = [UIFont systemFontOfSize:13];
    tiaojkuan.textColor = [UIColor blackColor];
    tiaojkuan.userInteractionEnabled = YES;
    [self.view addSubview:tiaojkuan];
    
    NSMutableAttributedString * att = [[NSMutableAttributedString alloc]initWithString:@"注册账号即代表我同意蓄锐广场的服务条款"];
    [att addAttributes:@{NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle]} range:NSMakeRange(15, 4)];
    tiaojkuan.attributedText = att;
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tiaokuanAction)];
    [tiaojkuan addGestureRecognizer:tap];
    
    [self locationStart];
}

-(void)tiaokuanAction
{
    WebViewController * kwb = [[WebViewController alloc]init];
    kwb.title = @"服务条款";
    kwb.url = @"https://app.xrsquare.com/private";
    [self.navigationController pushViewController:kwb animated:YES];
}

-(void)login
{
    LoginAccountViewController * login = [[LoginAccountViewController alloc]init];
    [self.navigationController pushViewController:login animated:YES];
}

-(void)wechatLogin
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:self completion:^(id result, NSError *error) {
        
        UMSocialUserInfoResponse *resp = result;
        NSLog(@"%@",resp);
        if (error) {
            
        }
        else
        {
            [NetRequestCenter wechatLoginWithProvince:province city:city openid:resp.openid unionid:resp.unionId accesstoken:resp.accessToken result:^(BOOL success, NSDictionary *resultDic) {
                if (success) {
                    HomeViewController * home = [[HomeViewController alloc]init];
                    SortViewController * sort = [[SortViewController alloc]init];
                    GrowViewController * grow = [[GrowViewController alloc]init];
                    MyViewController * my = [[MyViewController alloc]init];
                    
                    MMNavController * homen = [[MMNavController alloc]initWithRootViewController:home];
                    homen.tabBarItem.title = @"首页";
                    homen.tabBarItem.image = [[UIImage imageNamed:@"首页-normal"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    homen.tabBarItem.selectedImage = [[UIImage imageNamed:@"首页-highlight"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    
                    MMNavController * sortn = [[MMNavController alloc]initWithRootViewController:sort];
                    sortn.tabBarItem.title = @"分类";
                    sortn.tabBarItem.image = [[UIImage imageNamed:@"分类-normal"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    sortn.tabBarItem.selectedImage = [[UIImage imageNamed:@"分类-highlight"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    
                    MMNavController * grown = [[MMNavController alloc]initWithRootViewController:grow];
                    grown.tabBarItem.title = @"成长";
                    grown.tabBarItem.image = [[UIImage imageNamed:@"成长-normal"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    grown.tabBarItem.selectedImage = [[UIImage imageNamed:@"成长-highlight"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    
                    MMNavController * myn = [[MMNavController alloc]initWithRootViewController:my];
                    myn.tabBarItem.title = @"我的";
                    myn.tabBarItem.image = [[UIImage imageNamed:@"我的-normal"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    myn.tabBarItem.selectedImage = [[UIImage imageNamed:@"我的-highlight"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    
                    UITabBarController * tabbar = [[UITabBarController alloc]init];
                    tabbar.tabBar.tintColor = [UIColor redColor];
                    tabbar.viewControllers = @[homen,sortn,grown,myn];
                    tabbar.tabBar.tintColor = themeColor;
                    
                    [UIApplication sharedApplication].keyWindow.rootViewController = tabbar;

                }
            }];
        }
    }];
}

-(void)qqLogin
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_QQ currentViewController:self completion:^(id result, NSError *error) {
        
        UMSocialUserInfoResponse *resp = result;
        
        if (error) {
            
        }
        else
        {
            [NetRequestCenter qqloginWithOpenid:resp.openid nickname:resp.name sex:resp.gender pic:resp.iconurl province:province city:city result:^(BOOL success, NSDictionary *resultDic) {
                if (success) {
                    HomeViewController * home = [[HomeViewController alloc]init];
                    SortViewController * sort = [[SortViewController alloc]init];
                    GrowViewController * grow = [[GrowViewController alloc]init];
                    MyViewController * my = [[MyViewController alloc]init];
                    
                    MMNavController * homen = [[MMNavController alloc]initWithRootViewController:home];
                    homen.tabBarItem.title = @"首页";
                    homen.tabBarItem.image = [[UIImage imageNamed:@"首页-normal"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    homen.tabBarItem.selectedImage = [[UIImage imageNamed:@"首页-highlight"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    
                    MMNavController * sortn = [[MMNavController alloc]initWithRootViewController:sort];
                    sortn.tabBarItem.title = @"分类";
                    sortn.tabBarItem.image = [[UIImage imageNamed:@"分类-normal"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    sortn.tabBarItem.selectedImage = [[UIImage imageNamed:@"分类-highlight"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    
                    MMNavController * grown = [[MMNavController alloc]initWithRootViewController:grow];
                    grown.tabBarItem.title = @"成长";
                    grown.tabBarItem.image = [[UIImage imageNamed:@"成长-normal"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    grown.tabBarItem.selectedImage = [[UIImage imageNamed:@"成长-highlight"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    
                    MMNavController * myn = [[MMNavController alloc]initWithRootViewController:my];
                    myn.tabBarItem.title = @"我的";
                    myn.tabBarItem.image = [[UIImage imageNamed:@"我的-normal"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    myn.tabBarItem.selectedImage = [[UIImage imageNamed:@"我的-highlight"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    
                    UITabBarController * tabbar = [[UITabBarController alloc]init];
                    tabbar.tabBar.tintColor = [UIColor redColor];
                    tabbar.viewControllers = @[homen,sortn,grown,myn];
                    tabbar.tabBar.tintColor = themeColor;
                    
                    [UIApplication sharedApplication].keyWindow.rootViewController = tabbar;

                }
            }];
        }
    }];
}

-(void)home
{
    HomeViewController * home = [[HomeViewController alloc]init];
    [self.navigationController pushViewController:home animated:YES];
    
    self.navigationController.navigationBar.hidden = NO;
}

-(void)create
{
    RegisterViewController * create = [[RegisterViewController alloc]init];
    [self.navigationController pushViewController:create animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
